//
//  RootViewController.m
//  XMLtoCD08
//
//  Created by Miles on 10-03-24.
//  Copyright Miles Thorogood
//  greenmeat.net 2010. All rights reserved.
//

#import "RootViewController.h"
#import "ArtistViewController.h"
#import "ArtworkViewContoller.h"

#import "ProgramViewController.h"

#import "Artist.h"
#import "AddNewArtist.h"
#import "GC_XMLParser.h"

@implementation RootViewController

@synthesize fetchedResultsController, managedObjectContext;
@synthesize artistsFromXML ;
@synthesize splashView ;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

	self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"] ;
	
	
	NSString *url = @"http://greenmeat.net/artistList4.xml" ;
	NSString *parentTag = @"ec_gradsubmission" ;
	NSArray *tags = [[[NSArray alloc] initWithObjects:@"last_name", @"first_name", @"program_type", @"medium", @"text", @"timestamp",@"filepath", nil] autorelease];
	artistsFromXML = [[GC_XMLParser alloc] initWithObjects:url parent:parentTag elements:tags] ;
	
	NSError *error = nil;
	if (![[self fetchedResultsController] performFetch:&error]) {
		/*
		 Replace this implementation with code to handle the error appropriately.
		 
		 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
		 */
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
	}
	
	//[self deleteAllObjects:@"Artist"] ;
	
	[self insertNewObject] ;
	
}

-(void)showSplash
{
	UIViewController *modalViewController = [[UIViewController alloc] init];
	modalViewController.view = splashView;
	[self presentModalViewController:modalViewController animated:NO];
	[self performSelector:@selector(hideSplash) withObject:nil afterDelay:3.0];
}
//hide splash screen
- (void)hideSplash{
	[[self modalViewController] dismissModalViewControllerAnimated:YES];
}

- (void)dealloc {
	[fetchedResultsController release];
	[managedObjectContext release];
	[artistsFromXML release] ;
    [super dealloc];
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

- (void)viewDidUnload {
	// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
	// For example: self.myOutlet = nil;
}

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */


#pragma mark -
#pragma mark Add a new object

- (void)insertNewObject {
	
	for (int artistIndex=0; artistIndex<[artistsFromXML count]; artistIndex++) {
		Artist *artist = (Artist *) [NSEntityDescription insertNewObjectForEntityForName:@"Artist" inManagedObjectContext:managedObjectContext];
		AddNewArtist *newArtist = [[AddNewArtist alloc] init] ;
		newArtist.artist = artist ;
		
		[newArtist populateArtist:[artistsFromXML objectAtIndex:artistIndex] ];
		//NSString *name = [[artistsFromXML objectAtIndex:artistIndex] objectForKey:@"last_name"] ;
		[newArtist release] ;
	}
}

- (NSDate *) stringToDate:(NSString *) datestring {	
	// Convert string to date object
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	[dateFormat setDateFormat:@"yyyy-MM-dd"];
	NSDate *date = [dateFormat dateFromString:datestring];  
	
	// Convert date object to desired output format
	[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
	datestring = [dateFormat stringFromDate:date];  
	[dateFormat release];
	NSLog(@"date is %@", datestring) ;
	
	return date ;
}

#pragma mark -
#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[fetchedResultsController sections] count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	static NSString *kCellIdentifier = @"Cell";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
    }
    Artist *artist = [fetchedResultsController objectAtIndexPath:indexPath];
    //Year *song = [fetchedResultsController objectAtIndexPath:indexPath];
	//NSLog(@"%@", [artist stream] );
	cell.textLabel.text = [artist lastname] ;//[NSString stringWithFormat:NSLocalizedString(@"#%d %@", @"#%d %@"), [song.rank integerValue], song.title];
	cell.imageView.image = [artist artistThumbnailImage] ;
	return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	/*
	//ArtistViewController *artistView = [[ArtistViewController alloc] initWithNibName:@"ArtistViewController" bundle:nil] ;
	ArtworkViewContoller *artworkView = [[ArtworkViewContoller alloc] initWithNibName:@"ArtworkViewContoller" bundle:nil] ;
	
	Artist *artist = [fetchedResultsController objectAtIndexPath:indexPath];
	//artistView.artist = artist ;
	artworkView.artist = artist ;
	
	// Pass the selected object to the new view controller.
	[self.navigationController pushViewController:artworkView animated:YES];
	
	[artworkView release];
	
	*/
	ProgramViewController *programView = [[ProgramViewController alloc] initWithNibName:@"ProgramViewController" bundle:nil] ;
	programView.managedObjectContext = managedObjectContext ;
	
	[self.navigationController pushViewController:programView animated:YES] ;
	
	[programView release] ;
	/*
	NSString *imageURL = [artist filepath] ;
	
	NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
	UIImage *artistlImage = [[UIImage alloc] initWithData:imageData];
	artistView.imageView.image = artistlImage;
	
	[artistView.textView setText:[artist text]] ;
	
	[artistView release];
	
	*/
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the managed object for the given index path
		NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
		[context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]];
		
		// Save the context.
		NSError *error = nil;
		if (![context save:&error]) {
			/*
			 Replace this implementation with code to handle the error appropriately.
			 
			 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
			 */
			NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
			abort();
		}
	}   
}


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // The table view should not be re-orderable.
    return NO;
}


#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController {
    
    if (fetchedResultsController != nil) {
        return fetchedResultsController;
    } else if (fetchedResultsController == nil) {
        NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
		NSEntityDescription *entity = [NSEntityDescription entityForName:@"Artist" inManagedObjectContext:managedObjectContext];
		[fetchRequest setEntity:entity];
		
		/*
		 NSString *artistYear = @"2010" ;
		 NSPredicate *predicate = [NSPredicate predicateWithFormat:
		 @"year contains [c] %@", artistYear];
		 
		 //NSLog( @"predicate = %@", predicate ); 
		 [fetchRequest setPredicate:predicate] ;
		 */
		NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"lastname" ascending:YES] autorelease];
		NSArray *sortDescriptors = [[[NSArray alloc] initWithObjects:sortDescriptor, nil] autorelease];
		
        [fetchRequest setSortDescriptors:sortDescriptors];
        fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
		
		NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
		aFetchedResultsController.delegate = self;
		self.fetchedResultsController = aFetchedResultsController;
	
	}
   	return fetchedResultsController;
}    

- (void) deleteAllObjects: (NSString *) entityDescription  {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
	
    NSError *error;
    NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    [fetchRequest release];
	
	
    for (NSManagedObject *managedObject in items) {
        [managedObjectContext deleteObject:managedObject];
		// NSLog(@"%@ object deleted",entityDescription);
    }
    if (![managedObjectContext save:&error]) {
        NSLog(@"Error deleting %@ - error:%@",entityDescription,error);
    }
	
}

// NSFetchedResultsControllerDelegate method to notify the delegate that all section and object changes have been processed. 
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
	// In the simplest, most efficient, case, reload the table view.
	[self.tableView reloadData];
}

/*
 Instead of using controllerDidChangeContent: to respond to all changes, you can implement all the delegate methods to update the table view in response to individual changes.  This may have performance implications if a large number of changes are made simultaneously.

// Notifies the delegate that section and object changes are about to be processed and notifications will be sent. 
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
	[self.tableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
	// Update the table view appropriately.
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
	// Update the table view appropriately.
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
	[self.tableView endUpdates];
} 
 */


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
	// Relinquish ownership of any cached data, images, etc that aren't in use.
}




@end

